import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Image,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { Link } from 'react-router-dom'
import { ArticleListState } from 'api/constant'
import { delArticle, getArticleList } from 'api/article'
import Channel from 'components/Channel'
import defaultImg from 'assets/error.png'

const { confirm } = Modal

const { RangePicker } = DatePicker

export default class index extends Component {
  state = {
    dataSource: [],
    page: 1,
    page_size: 10,
    total_count: 0,
  }
  params = {}
  columns = [
    {
      title: '封面',
      dataIndex: ['cover', 'images', '0'],
      key: 'images',
      render(src) {
        return (
          <Image
            width={200}
            height={150}
            src={src || defaultImg}
            preview={src ? true : false}
            fallback={defaultImg}
          />
        )
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 300,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render(val) {
        const tags = ArticleListState.find((item) => item.id === val)
        return <Tag color={tags.color}>{tags.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
    },
    {
      title: '操作',
      render: (row) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => this.onClickEdit(row.id)}
            />
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => this.onClickDel(row.id)}
            />
          </Space>
        )
      },
    },
  ]
  componentDidMount() {
    this.loadArticleList()
  }
  render() {
    const { dataSource, total_count, page_size, page } = this.state
    return (
      <div>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>文章列表</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form onFinish={this.onFinish} initialValues={{ status: -1 }}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleListState.map((item) => (
                  <Radio key={item.id} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            <Form.Item label="频道" name="channel_id">
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`共有${total_count}条数据`}>
          <Table
            dataSource={dataSource}
            columns={this.columns}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              current: page,
              pageSize: page_size,
              total: total_count,
              onChange: this.onPaginationChange,
            }}
          />
        </Card>
      </div>
    )
  }

  onClickDel = (id) => {
    confirm({
      title: '警告?',
      icon: <ExclamationCircleOutlined />,
      content: '确认删除？',
      onOk: async () => {
        try {
          await delArticle(id)
          message.success('删除成功!')
          this.loadArticleList()
          if (this.dataSource < 1 && this.page > 1) {
            this.setState({
              page: this.state.page - 1,
            })
          }
        } catch (err) {
          message.error('删除失败!')
        }
      },
      onCancel() {},
    })
  }
  onClickEdit = (id) => {
    this.props.history.push(`/home/publish/${id}`)
  }
  onFinish = (val) => {
    console.log(val)
    for (let key in val) {
      if (val[key] === undefined || val[key] === null || val[key] === -1) {
        delete val[key]
      }
    }

    if (val.date) {
      val.begin_pubdate = val.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      val.end_pubdate = val.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
      delete val.date
    }
    this.params = val
    this.setState({
      page: 1,
    })
    this.loadArticleList()
  }

  loadArticleList = async () => {
    try {
      const { page, page_size } = this.state
      const { data: res } = await getArticleList({
        page,
        per_page: page_size,
        ...this.params,
      })
      this.setState({
        dataSource: res.results,
        page: res.page,
        page_size: res.per_page,
        total_count: res.total_count,
      })
    } catch (err) {
      console.dir(err)
    }
  }
  onPaginationChange = (page, pageSize) => {
    this.setState(
      {
        dataSource: [],
        page,
        page_size: pageSize,
      },
      () => {
        this.loadArticleList()
      }
    )
  }
}
